﻿using Ly.Scheduler.Common;
using Ly.Scheduler.NewService;
using Quartz;
using SX.Utils.Log.log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ly.Scheduler.NewService
{ 
    [DisallowConcurrentExecution]
    public class PublicJob : IJob
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(PublicJob));
        private readonly JobActionService actionService = new JobActionService();
        private readonly BackgroundJobService jobService = new BackgroundJobService();
        public void Execute(IJobExecutionContext context)
        {
            logger.Debug("隐藏后台管理作业运行");
            LoopAction(  context);
            //string data = context.MergedJobDataMap["Parameters"].ToString();
            //BackgroundJob jobdata = SX.Utils.JsonHelper.ToObject<BackgroundJob>(data);
            //if (jobdata.Action == "RunOnce")
            //{
            //    var job = JobManager.CreateJob(jobdata);
            //    context.Scheduler.AddJob(job, true);
            //    context.Scheduler.TriggerJob(JobManager.CreateKey(jobdata.Id.Value));
            //}
            //else if (jobdata.Action == "Add")
            //{
            //    JobManager.ScheduleJob(context.Scheduler, jobdata);
            //}
            //else if (jobdata.Action == "Remove") {
            //    JobKey key = JobManager.CreateKey(jobdata.Id.Value);
            //    context.Scheduler.DeleteJob(key);
            //} 
        }
        
        private void LoopAction(IJobExecutionContext context)
        {
            JobAction action = null;
            action = actionService.GetUnExecAction(); // 查询未完成的动作
            while (action != null)
            {
                ExecAction(context,action); // 执行动作
                action = actionService.GetUnExecAction(); // 查询下一个未完成的动作
            }
        }
       
        private void ExecAction(IJobExecutionContext context,JobAction action) {

            string ActionName = action.Action.ToUpper();
            JobKey jobKey = JobManager.CreateKey(action.JobId);
            // 删除动作
            if (ActionName == "REMOVE")
            {
               
                if (context.Scheduler.CheckExists(jobKey))
                    context.Scheduler.DeleteJob(jobKey);
                actionService.CompleteAction(action.Id,"作业删除成功");
                return;
            }
            string actionResult = "什么都没做！";

            if (ActionName == "RUNONCE")
            {
                actionResult = RUNONCE(context, jobKey, action.JobId); 
            }
            else if (ActionName == "ADD") // 添加
            {
                actionResult = ADD(context, jobKey, action.JobId);
            }
            else if (ActionName == "UPDATE") // 编辑
            {
                actionResult = UPDATE(context, jobKey, action.JobId);
            }
            actionService.CompleteAction(action.Id, actionResult);
        }
        /// <summary>
        /// 执行一次作业
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobKey"></param>
        /// <param name="jobid"></param>
        /// <returns></returns>
        private string RUNONCE(IJobExecutionContext context, JobKey jobKey, Guid jobid) {
            if (!context.Scheduler.CheckExists(jobKey))
            {
                BackgroundJob jobdata = jobService.GetJob(jobid);
                if (jobdata == null)
                {
                    return "作业不存在！";
                }
                var job = JobManager.CreateJob(jobdata);
                context.Scheduler.AddJob(job, true);
            }
            context.Scheduler.TriggerJob(jobKey);
            return "执行一次作业完成";

        }


        /// <summary>
        /// 添加作业
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobKey"></param>
        /// <param name="jobid"></param>
        /// <returns></returns>
        private string ADD(IJobExecutionContext context, JobKey jobKey, Guid jobid)
        {
            if (context.Scheduler.CheckExists(jobKey))
                context.Scheduler.DeleteJob(jobKey);
            BackgroundJob jobdata = jobService.GetJob(jobid);
            if (jobdata == null)
            {
                return "作业不存在！";
            }
            JobManager.ScheduleJob(context.Scheduler, jobdata); 
            return "添加作业完成"; 
        }

        /// <summary>
        /// 更新作业
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobKey"></param>
        /// <param name="jobid"></param>
        /// <returns></returns>
        private string UPDATE(IJobExecutionContext context, JobKey jobKey, Guid jobid)
        {
            if (context.Scheduler.CheckExists(jobKey))
                context.Scheduler.DeleteJob(jobKey);
            BackgroundJob jobdata = jobService.GetJob(jobid);
            if (jobdata == null)
            {
                return "作业不存在！";
            }
            JobManager.ScheduleJob(context.Scheduler, jobdata);
            return "更新作业完成";
        }
    }
}
